import fetchInstance from './request/axios'
import { BASE_URL, BASE_URL_AMAP, TIME_OUT } from './request/config'
import cache from '@/utils/cache'
import message from '@/utils/message'
// import { mapDoSecret } from "@/utils/secret"

// 记录接口地址
let interfaceUrl = ''

// 可以new多个fetchInstance 防止项目多个接口地址
const fetch = new fetchInstance({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config) => {
      interfaceUrl = config.url
      if (config.url.includes('mediaAudio') || config.url.includes('acEvents')) {
        config.headers["Content-Type"] = "multipart/form-data"
      } else {
        config.headers["Content-Type"] = "application/json"
      }

      const token = cache.getCache('token')
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      // 加密
      // return mapDoSecret(config)
      // 不加密
      return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      if (res.data.code === 500) {
        message.error(res.data.msg)
        console.error("报错的接口地址:", interfaceUrl)
        throw new Error()
      }
      if (res.data.code === 401) {
        message.error("登录失效，请重新登录")
        cache.removeCache('token')
        throw new Error()
      }
      return res.data
    },
    responseInterceptorCatch(err) {
      return err
    }
  }
})

const fetchAmap = new fetchInstance({
  baseURL: BASE_URL_AMAP,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config) => {
      return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      return res
    },
    responseInterceptorCatch(err) {
      return err
    }
  }
})

export {
  fetch,
  fetchAmap
}
